import React from 'react';
import Taro from '@tarojs/taro';

import {connect} from 'react-redux';
import * as T from './types';
import actions from './actions';
import {store2Props} from './selectors';

import {View, Image, ScrollView, Button} from '@tarojs/components';
import './index.less';
import {
  OSS_PATH_PREFIX,
  OSS_BASE_PATH_PREFIX,
  SYNTHETCI_SEELCT_IP_STORE,
  EMPTY_IMAGE,
  IMAGE_EMPTY,
  CODE_SUCCESS,
  GAME_SHARE_TITLE,
  TASK_CONDITION_TYPE,
  SYNTHETCI_SELECT_PROP_STORE,
  SYNTHETCI_SELECT_TASK,
} from './constant';
import 'taro-ui/dist/style/components/flex.scss';
import 'taro-ui/dist/style/components/icon.scss';
import classNames from 'classnames';

import StrategyModal from './components/StrategyModal/StrategyModal';
import DailyExclusiveModal from './components/DailyExclusiveModal/DailyExclusiveModal';
import PageLoading from '../../common/PageLoading';
import TaskModal from './components/TaskModal/TaskModal';
import PropModal from './components/PropModal/PropModal';
import AdvModal from '@/pages/common/adv-modal/adv-modal';
import MemberModal from './components/MemberModal/MemberModal';

import CustomScrollView from '@/common/scrollview';
import {handleUrl, fetchModal, setModalShow} from 'wmkit';

actions().actions.loadReducer();

// @ts-ignore
@connect<Partial<T.IProps>, any>(store2Props, actions)
export default class SyntheticCardIpPa extends React.Component<Partial<T.IProps>, any> {
  // 使用state值
  constructor(props) {
    super(props);
    this.state = {
      query: {},
      pics: {
        title: OSS_PATH_PREFIX + '/gameTitle.png',
        loadingIcon: OSS_BASE_PATH_PREFIX + '/gameLoadingWhite.png',
        emptyIcon: OSS_BASE_PATH_PREFIX + '/empty.png',
        gameShareIcon: OSS_BASE_PATH_PREFIX + '/gameShareIcon.png', // 分享至朋友圈
        gameShareThum: OSS_BASE_PATH_PREFIX + '/gameShareThum.png', // 分享缩略图
        propBuffIcon: OSS_BASE_PATH_PREFIX + '/propBuffIcon.png', // 道具图标
      },
      emptyText: 'IP系列添加中,敬请期待...',
      OPEARTE: [
        {
          label: '我的卡库',
          className: 'myCard',
          url: OSS_PATH_PREFIX + '/ipIcon.png',
          func: 'handleMyLibrary',
        },
        {
          label: '领福利',
          className: 'myTask',
          url: OSS_BASE_PATH_PREFIX + '/giftIcon.png',
          func: 'handleMyTasks',
        },
      ],

      selectId: -1,

      // 模态框显示
      modal: {
        type: '', // 多个模态框
        visible: false,
        item: null,
      },

      // loading加载
      loading: {
        status: false,
        text: '',
        style: {
          border: '8rpx solid #fff',
        },
      },

      selectedProp: null, // 选择道具
      imageError: {},

      // 广告
      adModal: {
        isModalFlag: false,
        imgUrl: '',
        jumpPage: {},
        nextPopupId: '',
        type: 'magicDrawCardHome',
      },
    };
  }

  componentDidShow() {
    this.handleGetRouterParams(); // 获取路由参数
    this.handleAdModalUpdateStatus(''); // 广告弹出
    this.props.actions.init();
  }

  componentWillUnmount() {
    this.props.actions.clean();
  }

  componentWillReceiveProps(nextProps, nextContext: any): void {
    // 查询每日游戏次数如果有信息，则不进行弹框提示
    if (nextProps.main.status.loadingGameDaily == false && this.props.main.status.loadingGameDaily == true) {
      // 无信息则弹出开心收下弹框
      if (nextProps.main.response.loadGameDaily == CODE_SUCCESS) {
        console.log('index.tsx 今日领取记录');
        if (!nextProps.main.gameReceiveInfo.id) {
          this.handleModalShowAndHide('dailyExclusive', true);
        } else {
          this.handleModalShowAndHide('', false);
        }
      }

      this.handleGameAvailableTimes(); // 获取游戏次数
    }

    // 做任务
    if (nextProps.main.status.computingTask == false && this.props.main.status.computingTask == true) {
      console.log('index.tsx 做任务', nextProps.main.response.computedTask);
      if (nextProps.main.response.computedTask == CODE_SUCCESS) {
        this.handleTaskSuccess();
      }
    }
  }

  /**
   * 做任务成功后的回调
   */
  handleTaskSuccess = () => {
    this.handleGameAvailableTimes(); //查询游戏次数
    this.handleQueryTaskItems({pageNum: 0});
  };

  /**
   * 获取路由参数
   */
  handleGetRouterParams = () => {
    let params = Taro.getCurrentInstance()?.router?.params;
    console.log('syntheticCardIp index.tsx handleGetRouterParams params', params);

    params = params || {};

    if (params.favorite || params.share) {
      Taro.redirectTo({
        url: '/pages/package-I/home/index',
      });
      return;
    }

    this.handleQuery(); // 查询信息

    this.setState({
      query: params,
    });

    // 判断上一级是哪个页面，如果是合卡或者是我的卡库页面，则从缓存里取id
    const pages = Taro.getCurrentPages();
    let currPage = pages[pages.length - 1];
    let showReferpagepath = currPage.__displayReporter.showReferpagepath;

    // 任务中心携带参数
    if (params && params.taskConditionsType && params.taskId) {
      // 已做完任务清空了
      if (showReferpagepath == 'pages/package-I/syntheticCard/index.html') {
        // 游戏结束后的任务
        let selectTask = Taro.getStorageSync(SYNTHETCI_SELECT_TASK);
        if (!selectTask) {
          Taro.removeStorageSync(SYNTHETCI_SELECT_TASK);
        }
        // 还没开始做任务
        else {
          Taro.setStorageSync(SYNTHETCI_SELECT_TASK, {
            taskConditionsType: params.taskConditionsType,
            taskId: params.taskId,
          });
        }
      }

      // 其他页面进来的
      else {
        Taro.setStorageSync(SYNTHETCI_SELECT_TASK, {
          taskConditionsType: params.taskConditionsType,
          taskId: params.taskId,
        });
      }
    } else {
      // 非卡库和合卡页面都删掉库存
      if (
        showReferpagepath != 'pages/package-I/syntheticCard/index.html' &&
        showReferpagepath != 'pages/package-I/syntheticCardLibrary/index.html'
      ) {
        Taro.removeStorageSync(SYNTHETCI_SELECT_TASK);
      }
    }

    // 道具、选择ip处理
    if (
      showReferpagepath !== 'pages/package-I/syntheticCard/index.html' &&
      showReferpagepath !== 'pages/package-I/syntheticCardLibrary/index.html' &&
      showReferpagepath !== 'pages/package-I/syntheticCardIp/index.html'
    ) {
      Taro.removeStorageSync(SYNTHETCI_SEELCT_IP_STORE);
      Taro.removeStorageSync(SYNTHETCI_SELECT_PROP_STORE); // 删除选择道具
      this.setState({
        selectId: -1,
        selectedProp: null,
      });
    } else {
      let selectIpStorage = Taro.getStorageSync(SYNTHETCI_SEELCT_IP_STORE);
      console.log('index.tsx selectIpStorage', selectIpStorage);

      if (selectIpStorage) {
        this.setState({
          selectId: selectIpStorage.ipId,
        });
      }

      let selectPropStorage = Taro.getStorageSync(SYNTHETCI_SELECT_PROP_STORE);
      console.log('index.tsx selectPropStorage=', selectPropStorage);
      if (selectPropStorage && selectPropStorage.id) {
        this.setState({
          selectedProp: selectPropStorage,
        });
      }
    }
  };

  /**
   * 查询信息
   */
  handleQuery = () => {
    this.handleQueryUserInfo(); // 查询用户信息
    this.handleQueryGameInfo(); // 查询游戏信息
    this.handleQueryIpItems(); // 查询卡片列表
    this.handleQueryTaskItems({}); // 查询游戏任务列表
    this.handleQueryPropItems(); // 查询道具列表
  };

  /**
   * 查询道具
   */
  handleQueryPropItems = (pagation = {}) => {
    const {
      main: {
        prop: {page},
      },
    } = this.props;
    let params = {
      ...page,
      ...pagation,
    };
    this.props.actions.action.loadPropItems(params);
  };

  /**
   * 查询会员信息
   */
  handleQueryUserInfo = () => {
    let params = {};
    this.props.actions.action.loadUserInfo(params);
  };

  /**
   * 查询每日领取次数
   */
  handleQueryGameTimesDaily = (type) => {
    console.log('index.tsx handleQueryGameTimesDaily type', type);
    let params = {
      delFlag: type,
    };
    this.props.actions.action.loadGameTimesDaily(params);
  };

  /**
   * 获取用户可用游戏次数限制
   */
  handleGameAvailableTimes = () => {
    let params = {};
    this.props.actions.action.loadGameTimes(params);
  };

  /**
   * 查询游戏信息
   */
  handleQueryGameInfo = () => {
    let params = {};
    this.props.actions.action.loadGameInfo(params);
  };

  /**
   * 查询游戏任务列表
   */
  handleQueryTaskItems = (pagation) => {
    // 编辑参数
    const {
      main: {
        task: {page},
      },
    } = this.props;
    let params = {
      ...page,
      ...pagation,
    };
    this.props.actions.action.loadTaskItems(params);
  };

  /**
   * 查询ip列表
   */
  async handleQueryIpItems() {
    console.log('index.tsx handleQueryIpItems');
    // 编辑参数
    let params = {};
    this.props.actions.action.loadIpItems(params);
  }

  /**
   * 渲染
   * @returns
   */
  render() {
    if (!this.props.main) return null;
    let {
      main: {
        isLoading,
        ipItems,
        status: {loadingIp},
      },
    } = this.props;
    console.log(isLoading);

    return (
      <View className="pageSyntheticCardIpPa" catchMove>
        <View className="pageSyntheticCardIpContent">
          {this.renderStrategyContent()}
          {this.renderTitle()}
          {ipItems.length > 0 ? (
            <>
              {this.renderExtraIpMessage()}
              {this.renderIpList(ipItems)}
              {this.renderGameTimes()}
              {this.renderGameButton()}
            </>
          ) : (
            <></>
          )}
          {this.renderOperate()}
          {this.renderStrategyModal()}
          {this.renderTaskModal()}
          {this.renderDailyExclusiveModal()}
          {this.renderPropModal()}
          {this.renderAdvModal()}
          {this.renderMemberModal()}
        </View>
      </View>
    );
  }

  /**
   * 渲染道具模态框
   */
  renderPropModal() {
    const {
      modal: {visible, type, item},
      selectedProp,
    } = this.state;
    console.log('catchPlaything renderPropModal selectProp', selectedProp);

    return (
      <PropModal
        selectItem={selectedProp}
        visible={type == 'propEffect'}
        onCancel={(type) => this.handleCancelSelectProp(type)}
        onUse={this.handleUseSelectProp}
        onQueryProp={this.handleQueryPropItems}
      />
    );
  }

  /**
   * 取消道具使用
   */
  handleCancelSelectProp = (type) => {
    // 取消选中就不关
    if (type != 'selectedCancel') {
      this.handleModalShowAndHide('', false); // 关闭模态框
    } else {
      this.setState({
        selectedProp: null,
      });
      Taro.removeStorageSync(SYNTHETCI_SELECT_PROP_STORE); // 删除缓存
    }
  };

  /**
   * 选择道具
   */
  handleUseSelectProp = (data) => {
    this.setState({
      selectedProp: data,
    });
    this.handleModalShowAndHide('', false); // 关闭模态框
    Taro.setStorageSync(SYNTHETCI_SELECT_PROP_STORE, data); // 存缓存
  };

  /**
   * 渲染加载内容
   * @returns
   */
  renderLoadingContent() {
    const {
      loading: {style},
    } = this.state;
    return (
      <View className="loadingContent">
        <PageLoading style={style} />
      </View>
    );
  }

  /**
   * 渲染欧气攻略
   */
  renderStrategyContent() {
    return (
      <View className="strategy" onClick={this.handleStrategy}>
        <View className="strategyLabel">欧气攻略</View>
      </View>
    );
  }

  /**
   * 点击欧气攻略
   */
  handleStrategy = () => {
    this.handleModalShowAndHide('strategy', true);
  };

  /**
   * 渲染标题
   * @returns
   */
  renderTitle() {
    const {
      pics: {title},
    } = this.state;
    return (
      <View>
        <Image src={title} className="titleImage" mode="aspectFit" />
      </View>
    );
  }

  /**
   * 渲染标题
   * @returns
   */
  renderExtraIpMessage() {
    const {selectId} = this.state;
    let {
      main: {ipItems},
    } = this.props;
    console.log('index.tsx renderExtraMessgae ipItems', ipItems);
    console.log('index.tsx renderExtraIpMessage selectId', selectId);

    let currentIp = ipItems.find((i) => i.ipId == selectId);
    return (
      <View className="syntheticTitle">
        <View className="titleMessage">
          {currentIp && currentIp.ipId ? '您已选择: ' + currentIp.ipName : '选择你喜欢的IP'}
        </View>
        <View className="titleExtra">集齐卡片100%获得奖励</View>
      </View>
    );
  }

  /**
   * 渲染游戏次数
   * @returns
   */
  renderGameTimes() {
    const {
      main: {userInfo},
    } = this.props;
    return <View className="gameTimes">剩余次数: {userInfo.gameAvailableTimes}</View>;
  }

  /**
   * 渲染空
   */
  renderEmptyContent() {
    const {
      pics: {emptyIcon},
      emptyText,
    } = this.state;

    return (
      <View className="emptyContent">
        <Image src={emptyIcon} className="emptyIcon" />
        <View className="emptyExtraTitle">{emptyText}</View>
      </View>
    );
  }

  /**
   * 渲染攻略弹框
   */
  renderStrategyModal() {
    const {
      modal: {visible, type},
    } = this.state;

    return (
      <StrategyModal visible={visible && type == 'strategy'} onCancel={() => this.handleModalShowAndHide('', false)} />
    );
  }

  /**
   * 渲染游戏任务
   */
  renderTaskModal() {
    const {
      modal: {visible, type},
    } = this.state;

    return (
      <TaskModal
        visible={visible && type == 'task'}
        onCancel={() => this.handleModalShowAndHide('', false)}
        onQueryTask={this.handleQueryTaskItems}
      />
    );
  }

  /**
   * 渲染每日领取奖励
   * @returns
   */
  renderDailyExclusiveModal() {
    const {
      modal: {visible, type},
    } = this.state;

    return (
      <DailyExclusiveModal
        visible={visible && type == 'dailyExclusive'}
        onCancel={this.handleCancelGameTimesDaily}
        onReceive={this.handleReceive}
      />
    );
  }

  /**
   * 点击开心收下
   */
  handleReceive = () => {
    console.log('index.tsx handleReceive');
    this.handleQueryGameTimesDaily(false); // 获取游戏次数
  };

  /**
   * 取消
   */
  handleCancelGameTimesDaily = () => {
    this.handleQueryGameTimesDaily(true); // 获取游戏次数
  };

  /**
   * 模态框的弹出和隐藏
   */
  handleModalShowAndHide = (type, visible, item = null) => {
    console.log('index.tsx handleModalShowAndHide type', type, 'visible', visible);

    this.setState({
      modal: {
        ...this.state.modal,
        type: visible ? type : '',
        visible,
        item,
      },
    });
  };

  /**
   * 渲染ipList
   * @returns
   */
  renderIpList(ipItems) {
    console.log('index.tsx renderIpList ipItems', ipItems);

    const {selectId} = this.state;

    console.log('renderIpList selectId', selectId, 'ipItems', ipItems);

    return (
      <CustomScrollView className="ipList" scrollY>
        <View className="ipContent">
          {ipItems.map((i: any, index: number) => (
            <View key={index} className="ipRow">
              <View
                onClick={() => this.handleSelectIp(i)}
                className={classNames('at-row', 'item', i.ipId == selectId ? 'activeItem' : '')}
              >
                <View
                  className={classNames('at-icon', 'at-icon-check-circle', 'activeIcon')}
                  style={{display: i.ipId == selectId ? 'block' : 'none'}}
                ></View>
                <View className="at-col at-col-5 left">
                  <Image
                    src={i.img || IMAGE_EMPTY}
                    className="ipThum"
                    mode="aspectFill"
                    onError={(e) =>
                      this.handleImageError(e, index, {
                        propName: 'ipItems',
                        imageState: 'img',
                      })
                    }
                  />
                </View>
                <View className="at-col at-col-7 right">
                  <View className="ipName">{i.ipName}</View>
                </View>
              </View>
            </View>
          ))}
        </View>
      </CustomScrollView>
    );
  }

  /**
   * 图片加载错误
   * @param e
   * @param index
   */
  handleImageError = (e, index, item) => {
    const {main} = this.props;
    const {propName, imageState} = item;
    let {imageError} = this.state;
    if (imageError[propName]) {
      imageError[propName] = imageError[propName].concat([index]);
    } else {
      imageError[propName] = [index];
    }
    let result = JSON.parse(JSON.stringify(main[propName]));
    let currentImage = imageError[propName];
    let ids = currentImage;
    ids.map((i) => {
      result[i] = {
        ...result[i],
        [imageState]: IMAGE_EMPTY,
      };
    });
    this.props.actions.action.commonChange('main.' + propName, result);
  };

  /**
   * 渲染去集卡
   * @returns
   */
  renderGameButton() {
    return (
      <Button className="collectBtn" onClick={() => this.handleCollectIp()}>
        去集卡
      </Button>
    );
  }

  /**
   * 选择ip
   */
  handleSelectIp = (i) => {
    console.log('index.tsx handleSelectIp i', i);

    this.setState({
      selectId: i.ipId,
    });
    Taro.removeStorageSync(SYNTHETCI_SEELCT_IP_STORE); // 删除缓存
    Taro.setStorageSync(SYNTHETCI_SEELCT_IP_STORE, {...i}); // 存入缓存
  };

  /**
   * 集卡
   */
  handleCollectIp = () => {
    // console.log('index.tsx handleCollectIp data=', data);

    const {selectId, query} = this.state;
    const {
      main: {userInfo, ipItems},
    } = this.props;
    console.log('index.tsx handleCollectIp selectId', selectId);

    if (selectId == -1) {
      Taro.showToast({
        title: '请先选择IP哦',
        icon: 'none',
        duration: 2000,
      });
      return;
    }

    let currentIp = ipItems.find((i) => i.ipId == selectId);
    console.log('index.tsx currentIp', currentIp);
    let url = '/pages/package-I/syntheticCard/index?id=' + selectId + '&name=' + currentIp.ipName;

    Taro.navigateTo({
      url,
    });
  };

  /**
   * 渲染操作
   * @returns
   */
  renderOperate() {
    const {OPEARTE} = this.state;
    return (
      <View className="operates">
        {this.renderPropOperate()}
        <View className="extraOperates">
          {OPEARTE.map((i: any, index: number) => (
            <View className="operateItem" key={index} onClick={() => this[i.func](i)}>
              <Image src={i.url} className="operateIcon" />
              <View className="operateLabel">{i.label}</View>
            </View>
          ))}
        </View>
      </View>
    );
  }

  /**
   * 渲染魔力进阶
   */
  renderPropOperate() {
    const {
      pics: {propBuffIcon},
    } = this.state;
    return (
      <View className="propItem" onClick={this.handlePropModal}>
        <Image src={propBuffIcon} className="operateIcon" />
        <View className="operateLabel">魔力进阶</View>
      </View>
    );
  }

  /**
   * 魔力进阶
   */
  handlePropModal = () => {
    this.handleModalShowAndHide('propEffect', true);
  };

  /**
   * 渲染我的卡库
   */
  handleMyLibrary = () => {
    console.log('index.tsx handleMyLibray');

    const {selectId} = this.state;
    console.log('index.tsx handleMyLibrary selectId', selectId);

    Taro.navigateTo({
      url: '/pages/package-I/syntheticCardLibrary/index?ipId=' + selectId,
    });
  };

  /**
   * 渲染我的福利
   */
  handleMyTasks = () => {
    const {
      main: {userInfo},
    } = this.props;

    // 非会员不能做任务，让他开会员
    if (!userInfo.accountType) {
      this.handleModalShowAndHide('member', true);
    } else {
      this.handleModalShowAndHide('task', true);
    }
  };

  /**
   * 分享好友
   * @param res
   * @returns
   */
  onShareAppMessage(res) {
    const {
      pics: {gameShareThum},
      query,
    } = this.state;
    if (query && query.taskConditionsType && query.taskConditionsType == TASK_CONDITION_TYPE['share']) {
      console.log('分享给好友');
      this.handleComputedTask(query);
    }

    return {
      title: GAME_SHARE_TITLE,
      path: '/pages/package-I/home/index',
      imageUrl: gameShareThum,
      query: 'share=true',
    };
  }

  /**
   * 完成任务
   */
  handleComputedTask = (data) => {
    console.log('index.tsx datadatadata', data);

    // 编辑参数
    let params = {
      id: data.taskId,
    };
    console.log('syntheticCardIp params', params);
    this.props.actions.action.computedTask(params);

    this.setState({
      query: {
        ...this.state.query,
        taskConditionsType: '',
        taskId: '',
      },
    });
  };

  /**
   * 渲染广告模态框
   */
  renderAdvModal() {
    const {
      adModal: {imgUrl, isModalFlag, jumpPage},
    } = this.state;
    return (
      <AdvModal
        imgUrl={imgUrl}
        handleUrl={() => handleUrl(jumpPage)}
        handleClose={() => this.handleCloseAtModal()}
        isModalFlag={isModalFlag}
      />
    );
  }

  /**
   * 关闭广告模态框
   */
  handleCloseAtModal = () => {
    const {adModal} = this.state;

    this.setState(
      {
        adModal: {
          ...adModal,
          isModalFlag: false,
        },
      },
      async () => {
        if (this.state.adModal.nextPopupId) {
          await this.handleAdModalUpdateStatus(this.state.adModal.nextPopupId);
        }
      },
    );
  };

  /**
   * 广告弹出
   * @param id
   */
  async handleAdModalUpdateStatus(id) {
    const {adModal} = this.state;
    const res = await fetchModal(adModal.type);
    let popupId = null;
    if (!id && res && res.length > 0) {
      popupId = res[0].popupId;
    } else {
      popupId = id;
    }
    const flagParams = await setModalShow(res, adModal.type, popupId);

    this.setState(
      {
        adModal: {
          ...adModal,
          isModalFlag: flagParams.showFlag,
          imgUrl: flagParams.imgUrl,
          jumpPage: (flagParams.jumpPage && JSON.parse(flagParams.jumpPage)) || '',
          nextPopupId: flagParams.nextPopupId,
        },
      },
      () => {
        if (this.state.adModal.nextPopupId && !this.state.adModal.isModalFlag) {
          this.isGo(this.state.adModal.nextPopupId);
        }
      },
    );
  }
  async isGo(id) {
    await this.handleAdModalUpdateStatus(id);
  }

  /**
   * 渲染会员弹框
   */
  renderMemberModal() {
    const {
      modal: {visible, type},
    } = this.state;

    return (
      <MemberModal
        visible={visible && type == 'member'}
        onCancel={() => this.handleModalShowAndHide('', false)}
        onActivate={() => this.handleActivateMember()}
      />
    );
  }

  /**
   * 确定开通会员
   */
  handleActivateMember = () => {
    this.handleModalShowAndHide('', false); // 关闭模态框
    // 跳转到开通会员界面
    Taro.redirectTo({
      url: '/pages/package-A/memberOpen/index',
    });
  };

  /**
   * 分享到朋友圈
   * @param res
   * @returns
   */
  onShareTimeline(res) {
    const {
      pics: {gameShareIcon},
    } = this.state;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    console.log('选择iponShareAppMessage res.target', res.target);
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      path: '/pages/package-I/home/index',
      query: 'share=true',
    };
  }

  /**
   * 收藏
   * @param res
   * @returns
   */
  onAddToFavorites(res) {
    const {
      pics: {gameShareIcon},
    } = this.state;

    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target);
    }
    return {
      title: GAME_SHARE_TITLE,
      imageUrl: gameShareIcon,
      query: 'favorite=true',
    };
  }
}
